package com.chenggcode.simple.log.config;

import com.chenggcode.simple.log.filter.LogTraceFilter;
import com.chenggcode.simple.log.filter.MyRequestLoggingFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.AbstractRequestLoggingFilter;
import org.springframework.web.filter.CommonsRequestLoggingFilter;

import java.util.List;

/**
 * @author Chenggcode
 * @date 2025/6/19 11:51
 */
@Configuration
public class LogConfig {

    @Bean
    public FilterRegistrationBean<LogTraceFilter> logTraceFilter() {
        FilterRegistrationBean<LogTraceFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new LogTraceFilter());
        registration.addUrlPatterns("/*");
        registration.setName("logTraceFilter");
        registration.setOrder(Integer.MIN_VALUE); // 确保它是第一个被调用的 Filter
        return registration;
    }

    private static final List<String> HEADERS = List.of("operator", "deviceUuid");
    @Bean
    public MyRequestLoggingFilter logFilter() {
        MyRequestLoggingFilter filter = new MyRequestLoggingFilter();
        filter.setIncludeClientInfo(true);
        filter.setIncludeHeaders(true);
        filter.setHeaderPredicate(HEADERS::contains);
        filter.setIncludeQueryString(true); // 包含查询参数
        filter.setIncludePayload(true);     // 包含请求体
        filter.setMaxPayloadLength(1024);   // 限制请求体日志长度（避免大字段溢出）
        return filter;
    }

    // @Slf4j
    // public static class A extends AbstractRequestLoggingFilter {
    //     @Override
    //     protected void beforeRequest(HttpServletRequest request, String message) {
    //         log.info(message);
    //     }
    //
    //     @Override
    //     protected void afterRequest(HttpServletRequest request, String message) {
    //         log.info(message);
    //     }
    // }

}
